package com.wing.order.controller.admin;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.cabinet.service.EnterpricceIdService;
import com.wing.cabinet.utils.ExcelUtils;
import com.wing.common.utils.PageResult;
import com.wing.order.model.response.CabInventoryProductRecordVO;
import com.wing.order.model.response.MaterialInventoryStatisticsReportVO;
import com.wing.order.service.CabInventoryProductRecordService;
import com.wing.product.model.entity.ProductCategory;
import com.wing.warehouse.model.entity.Warehouse;
import com.wing.warehouse.service.WarehouseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 *
 * @author
 */
@Slf4j
@Validated
@Api(value = "Admin-物料库存统计报表", tags = "#/order/materialInventoryStatisticsReport")
@RestController("materialInventoryStatisticsReportController")
@RequestMapping("order/admin/materialInventoryStatisticsReport")
@RequiredArgsConstructor
public class MaterialInventoryStatisticsReportController {

    private final CabInventoryProductRecordService cabInventoryProductRecordService;
    private final WarehouseService warehouseService;
    private final EnterpricceIdService enterpricceIdService;

    @ApiOperation(value = "查询物料库存统计报表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "skuCode", value="物料编号", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "skuName", value="物料名称", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "oldSpecCode", value="规格码", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "startCreateTime", value="开始时间", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "endCreateTime", value="结束时间", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<CabInventoryProductRecordVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "desc") String order
            ,Long warehouseId
            ,String skuCode
            ,String skuName
            ,String oldSpecCode
            ,String startCreateTime
            ,String endCreateTime
            ,String query
    ){

        Page<CabInventoryProductRecordVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", StrUtil.toUnderlineCase(sort));
            params.put("order", order);
        }
        if(null != warehouseId){
            params.put("warehouseId", warehouseId);
        }
        if(StringUtils.isNotBlank(skuCode)){
            params.put("skuCode", skuCode);
        }
        if(StringUtils.isNotBlank(skuName)){
            params.put("skuName", skuName);
        }
        if(StringUtils.isNotBlank(oldSpecCode)){
            params.put("oldSpecCode", oldSpecCode);
        }
        if (StringUtils.isNotBlank(startCreateTime)) {
            params.put("startCreateTime", startCreateTime);
        }
        if (StringUtils.isNotBlank(endCreateTime)) {
            params.put("endCreateTime", endCreateTime);
        }
        if (StringUtils.isNotBlank(query)){
            params.put("query",query);
        }
        params.put("categoryType", ProductCategory.CategoryType.purchase);
        //搜索
        IPage<CabInventoryProductRecordVO> list = cabInventoryProductRecordService.statisticsReport(pg, params);
        //关联相关业务属性
        list.getRecords().parallelStream().forEach(k -> {
            // 产品期初仓库集合
            List<Long> openingWarehouseIds = new ArrayList<>();
            // 产品结存仓库集合
            List<Long> balanceWarehouseIds = new ArrayList<>();
            if(StringUtils.isNotBlank(k.getOpeningWarehouseIds())){
                if(k.getOpeningWarehouseIds().indexOf(",") > 0){
                    List<String> idStrList = Arrays.asList(k.getOpeningWarehouseIds().split(","));
                    for (String id : idStrList) {
                        openingWarehouseIds.add(Long.parseLong(id));
                    }
                }else{
                    openingWarehouseIds.add(Long.parseLong(k.getOpeningWarehouseIds()));
                }
            }
            if(StringUtils.isNotBlank(k.getBalanceWarehouseIds())){
                if(k.getBalanceWarehouseIds().indexOf(",") > 0){
                    List<String> idStrList = Arrays.asList(k.getBalanceWarehouseIds().split(","));
                    for (String id : idStrList) {
                        balanceWarehouseIds.add(Long.parseLong(id));
                    }
                }else{
                    balanceWarehouseIds.add(Long.parseLong(k.getBalanceWarehouseIds()));
                }
            }

            // 查询期初数量(基础单位计)
            Integer openingQuantity = 0;
            if(StringUtils.isNotBlank(startCreateTime)){
                if(null != warehouseId){
                    Integer quantity = cabInventoryProductRecordService.getOpeningQuantity(warehouseId, k.getSkuCode(), startCreateTime);
                    if(quantity != null){
                        openingQuantity = quantity;
                    }
                }else {
                    for (Long id : openingWarehouseIds) {
                        Integer quantity = cabInventoryProductRecordService.getOpeningQuantity(id, k.getSkuCode(), startCreateTime);
                        if(quantity != null){
                            openingQuantity += quantity;
                        }
                    }
                }
            }
            k.setOpeningQuantity(openingQuantity);

            // 查询期初数量(包装计)
            Integer openingPackQuantity = 0;
            if(StringUtils.isNotBlank(startCreateTime)){
                if(null != warehouseId){
                    Integer quantity = cabInventoryProductRecordService.getOpeningPackQuantity(warehouseId, k.getSkuCode(), startCreateTime);
                    if(quantity != null){
                        openingPackQuantity = quantity;
                    }
                }else {
                    for (Long id : openingWarehouseIds) {
                        Integer quantity = cabInventoryProductRecordService.getOpeningPackQuantity(id, k.getSkuCode(), startCreateTime);
                        if(quantity != null){
                            openingPackQuantity += quantity;
                        }
                    }
                }
            }
            k.setOpeningPackQuantity(openingPackQuantity);

            // 查询结存数量(基础单位计)
            Integer balanceQuantity = 0;
            if(null != warehouseId){
                Integer quantity = cabInventoryProductRecordService.getBalanceQuantity(warehouseId, k.getSkuCode(), startCreateTime);
                if(quantity != null){
                    balanceQuantity = quantity;
                }
            }else {
                for (Long id : balanceWarehouseIds) {
                    Integer quantity = cabInventoryProductRecordService.getBalanceQuantity(id, k.getSkuCode(), endCreateTime);
                    if(quantity != null){
                        balanceQuantity += quantity;
                    }
                }
            }
            k.setBalanceQuantity(balanceQuantity);

            // 查询结存数量(包装计)
            Integer balancePackQuantity = 0;
            if(null != warehouseId){
                Integer quantity = cabInventoryProductRecordService.getBalancePackQuantity(warehouseId, k.getSkuCode(), startCreateTime);
                if(quantity != null){
                    balancePackQuantity = quantity;
                }
            }else {
                for (Long id : balanceWarehouseIds) {
                    Integer quantity = cabInventoryProductRecordService.getBalancePackQuantity(id, k.getSkuCode(), endCreateTime);
                    if(quantity != null){
                        balancePackQuantity += quantity;
                    }
                }
            }
            k.setBalancePackQuantity(balancePackQuantity);
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response, String startCreateTime, String endCreateTime, Long warehouseId){
        Map paramsMap = new HashMap();
        paramsMap.put("startCreateTime", startCreateTime);
        paramsMap.put("endCreateTime", endCreateTime);
        paramsMap.put("warehouseId", warehouseId);
        List<MaterialInventoryStatisticsReportVO> list = cabInventoryProductRecordService.export(paramsMap);
        //关联相关业务属性
        list.parallelStream().forEach(k -> {
            // 产品期初仓库集合
            List<Long> openingWarehouseIds = new ArrayList<>();
            // 产品结存仓库集合
            List<Long> balanceWarehouseIds = new ArrayList<>();
            if(StringUtils.isNotBlank(k.getOpeningWarehouseIds())){
                if(k.getOpeningWarehouseIds().indexOf(",") > 0){
                    List<String> idStrList = Arrays.asList(k.getOpeningWarehouseIds().split(","));
                    for (String id : idStrList) {
                        openingWarehouseIds.add(Long.parseLong(id));
                    }
                }else{
                    openingWarehouseIds.add(Long.parseLong(k.getOpeningWarehouseIds()));
                }
            }
            if(StringUtils.isNotBlank(k.getBalanceWarehouseIds())){
                if(k.getBalanceWarehouseIds().indexOf(",") > 0){
                    List<String> idStrList = Arrays.asList(k.getBalanceWarehouseIds().split(","));
                    for (String id : idStrList) {
                        balanceWarehouseIds.add(Long.parseLong(id));
                    }
                }else{
                    balanceWarehouseIds.add(Long.parseLong(k.getBalanceWarehouseIds()));
                }
            }

            // 查询期初数量(基础单位计)
            Integer openingQuantity = 0;
            if(StringUtils.isNotBlank(startCreateTime)){
                if(null != warehouseId){
                    Integer quantity = cabInventoryProductRecordService.getOpeningQuantity(warehouseId, k.getSkuCode(), startCreateTime);
                    if(quantity != null){
                        openingQuantity = quantity;
                    }
                }else {
                    for (Long id : openingWarehouseIds) {
                        Integer quantity = cabInventoryProductRecordService.getOpeningQuantity(id, k.getSkuCode(), startCreateTime);
                        if(quantity != null){
                            openingQuantity += quantity;
                        }
                    }
                }
            }
            k.setOpeningQuantity(openingQuantity);

            // 查询期初数量(包装计)
            Integer openingPackQuantity = 0;
            if(StringUtils.isNotBlank(startCreateTime)){
                if(null != warehouseId){
                    Integer quantity = cabInventoryProductRecordService.getOpeningPackQuantity(warehouseId, k.getSkuCode(), startCreateTime);
                    if(quantity != null){
                        openingPackQuantity = quantity;
                    }
                }else {
                    for (Long id : openingWarehouseIds) {
                        Integer quantity = cabInventoryProductRecordService.getOpeningPackQuantity(id, k.getSkuCode(), startCreateTime);
                        if(quantity != null){
                            openingPackQuantity += quantity;
                        }
                    }
                }
            }
            k.setOpeningPackQuantity(openingPackQuantity);

            // 查询结存数量(基础单位计)
            Integer balanceQuantity = 0;
            if(null != warehouseId){
                Integer quantity = cabInventoryProductRecordService.getBalanceQuantity(warehouseId, k.getSkuCode(), startCreateTime);
                if(quantity != null){
                    balanceQuantity = quantity;
                }
            }else {
                for (Long id : balanceWarehouseIds) {
                    Integer quantity = cabInventoryProductRecordService.getBalanceQuantity(id, k.getSkuCode(), endCreateTime);
                    if(quantity != null){
                        balanceQuantity += quantity;
                    }
                }
            }
            k.setBalanceQuantity(balanceQuantity);

            // 查询结存数量(包装计)
            Integer balancePackQuantity = 0;
            if(null != warehouseId){
                Integer quantity = cabInventoryProductRecordService.getBalancePackQuantity(warehouseId, k.getSkuCode(), startCreateTime);
                if(quantity != null){
                    balancePackQuantity = quantity;
                }
            }else {
                for (Long id : balanceWarehouseIds) {
                    Integer quantity = cabInventoryProductRecordService.getBalancePackQuantity(id, k.getSkuCode(), endCreateTime);
                    if(quantity != null){
                        balancePackQuantity += quantity;
                    }
                }
            }
            k.setBalancePackQuantity(balancePackQuantity);
        });
        String warehouseName = "";
        if(null != warehouseId){
            Warehouse warehouse = warehouseService.getById(warehouseId);
            warehouseName = warehouse.getName();
        }
        paramsMap.put("warehouseName", warehouseName);
        ExcelUtils.bespokeExport(response, "物料库存报表", list, paramsMap, MaterialInventoryStatisticsReportVO.class);
    }

}
